#include "mainwindow.h"
#include "videoWidget.h"
#include <QKeyEvent>
#include <QMouseEvent>
#include <QDebug>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTimer>

VideoWidget::VideoWidget(QWidget *parent)
    : QVideoWidget(parent)
{
    setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);

    QPalette p = palette();
    p.setColor(QPalette::Window, Qt::black);
    setPalette(p);

    setAttribute(Qt::WA_OpaquePaintEvent);
    

    
}

//--------------------
// slot to run thread
//-------------------


void VideoWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape && isFullScreen()) {
        setFullScreen(false);
        event->accept();
    } else if (event->key() == Qt::Key_Enter && event->modifiers() & Qt::Key_Alt) {
        setFullScreen(!isFullScreen());
        event->accept();
    } else {
        QVideoWidget::keyPressEvent(event);
    }
}

void VideoWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
    setFullScreen(!isFullScreen());
    event->accept();
}

void VideoWidget::mousePressEvent(QMouseEvent *event)
{
    QVideoWidget::mousePressEvent(event);
}


void  videoWidget::clickedStop(){
    imageTimer->stop();
}

void videoWidget::run_thread()
{
   if (!otherThread->isRunning())
   {
      otherThread->start();
   }
}

//-------------------
// display the QImage
//-------------------




void videoWidget::displayImage(const QPixmap &image)
{
   mjpegImage->plot = image;
   mjpegImage->show();
   mjpegImage->update();
   mjpegImage->raise();
   mjpegImage->activateWindow();
}


videoWidget::videoWidget(QObject *parent) {
    setupUi(this);
    videoW = new VideoWidget(this);
    mainLayout->addWidget(videoW);
    connect(connectBtn,SIGNAL(clicked()),this,SLOT(clickedPlay()));
    connect(stopBtn,SIGNAL(clicked()),this,SLOT(clickedStop()));

    player = new QMediaPlayer(this);
    player->setVideoOutput(videoW);
    playlist = new QMediaPlaylist();
    player->setPlaylist(playlist);
    
    

    
    
        qRegisterMetaType<QImage>("QImage");
   otherThread = new timeConsumingThread(this);
   
      connect(otherThread, SIGNAL(theImage(const QPixmap &)),
           this, SLOT(displayImage(const QPixmap &)));
           mjpegImage = new ImageWindow();
           
    mjpegLayout->addWidget(mjpegImage);
    
    
        netImageHttp = new QNetworkAccessManager(this);
    connect(netImageHttp, SIGNAL(finished(QNetworkReply*)), this, SLOT(netImageHttpFinished(QNetworkReply*)));
  
  imageTimer = new QTimer();
  connect(imageTimer, SIGNAL(timeout()), this, SLOT(requestImage()));
    
  
}

void timeConsumingThread::netImageHttpFinished(QNetworkReply* reply){

 if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Error in" << reply->url() << ":" << reply->errorString();
        return;
    }
   
    QByteArray jpegData = reply->readAll();
    QPixmap pixmap;
    pixmap.loadFromData(jpegData);
    emit theImage(pixmap);



}


void videoWidget::netImageHttpFinished(QNetworkReply* reply){

 if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "Error in" << reply->url() << ":" << reply->errorString();
        return;
    }
   
    QByteArray jpegData = reply->readAll();
    QPixmap pixmap;
    pixmap.loadFromData(jpegData);
    //emit theImage(pixmap);
    displayImage(pixmap);

}

videoWidget::~videoWidget() {
    delete videoW;
}

void videoWidget::requestImage() {

    //QUrl url("C:/Users/Public/Videos/Sample Videos/Wildlife.wmv");
   
    
    QUrl url(QString("http://%1/cam_pic.php").arg(globalServer()));
    //QNetworkAcessManager http;
    QNetworkRequest request(url);
    netImageHttp->get(request);
    
    //run_thread();
    
    

    //playlist->clear();
    //playlist->addMedia(url);
    //player->play();
}

void videoWidget::clickedPlay() {
    qDebug() << "playClicked";
    imageTimer->start(1000/framePerSecSpinBox->value());
}


timeConsumingThread::timeConsumingThread(QObject *parent)
 : QThread(parent)
{

    netImageHttp = new QNetworkAccessManager(parent);
    connect(netImageHttp, SIGNAL(finished(QNetworkReply*)), this, SLOT(netImageHttpFinished(QNetworkReply*)));

}

//-----------------------
// run - paint the QImage
//-----------------------

void timeConsumingThread::run()
{
   
   /*
   QImage myQImage(600, 600, QImage::Format_RGB32);
   QPainter painter(&myQImage);
   for (int i=0; i<600; i++)
   {
      for (int j=0; j<600; j++)
      {
         double hue = (double)(i + j + i*j)/361200.0;
         QColor myColor;
         myColor.setHsvF(hue, 1.0, 1.0, 1.0);
         painter.setPen(myColor);
         painter.drawPoint(i, j);
      }
   }
   
   */
   
    QUrl url("http://192.168.2.35/cam_pic.php");
    //QNetworkAcessManager http;
    QNetworkRequest request(url);
    netImageHttp->get(request);
    
    //QImage image(url.toLocalFile());
    
   //emit theImage(image);
}



ImageWindow::ImageWindow(QWidget *parent) : QWidget(parent)
{
   setFixedSize(512, 288);
   setWindowTitle("Raspberry Pi Quad Cam");
}

//-----------------------------------------------------------------------------
//
// paint the image
//
//-----------------------------------------------------------------------------

void ImageWindow::paintEvent(QPaintEvent *)
{
   QPainter painter(this);
   painter.drawPixmap(0, 0, plot);
}
